package com.example.module_main.splash

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.Router
import com.example.lib_common.base.BaseActivity
import com.example.lib_common.getAttrValue
import com.example.lib_common.getUrlParams
import com.example.lib_common.getVersionCode
import com.example.lib_storage.AppMMKV
import com.example.module_main.R
import com.example.module_main.databinding.ActivitySplashBinding
import com.example.module_main.dialog.MessageNoticeDialog
import com.example.module_main.guide.GuideActivity
import com.example.module_main.main.MainActivity
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SplashActivity : BaseActivity<SplashViewModel,ActivitySplashBinding>(){
    override val mLayoutResId: Int
        get() = R.layout.activity_splash
    override val mViewModel: SplashViewModel by viewModels()

    //初始化结束后操作
    private var actionAfterInitFinished: (() -> Unit)? = null

    companion object{
        //倒计时
        private const val SPLASH_MAX_DELAY: Long = 1_500
    }
    private val mHandler by lazy{
        object : Handler(){
            override fun handleMessage(msg: Message) {
                if(AppMMKV.needGuide){
                    toGuide()
                }else{
                    toMain()
                }

            }
        }
    }

    override fun initView() {

    }

    @RequiresApi(Build.VERSION_CODES.P)
    override fun initData() {

        //点击通知栏打开

        //h5页面schema打开：获得参数--》根据参数跳转到不同的页面
        val query = intent.data?.query
        if(!query.isNullOrEmpty()){
            val map = getUrlParams(query)
            val type = map["type"].toString().toInt()
            val id = map["id"].toString()
            if(!isTaskRoot){//app在后台直接跳转到对应的页面
                handleLauchAppPramas(type,id)
            }else{
                //重新启动,保证闪屏倒计时完成后再跳转到对应的页面
                actionAfterInitFinished = {
                    handleLauchAppPramas(type,id)
                }
            }
        }
        //隐私协议对话框处理
        if(!AppMMKV.splashAgreement){

            val colorMain = getAttrValue(this, com.example.lib_common.R.attr.colorTheme)
            val userAgreement = "《用户协议》"
            val privacyPolicy = "《隐私政策》"
            val content = "宗申骑士俱乐部非常尊重用户个人的信息保护，我们依据最新的监管要求特向您说明如下：\n1.在使用 APP过程中，我们有可能会收集、使用设备标识信息用于推送车辆提醒消息。\n2.我们会一直采取严格的安全技术保护您的个人信息安全。\n3.未经您的同意，我们不会以协议约定之外的形式和渠道获取、共享或使用您的个人信息。\n您可通过阅读完整的${userAgreement}和${privacyPolicy}来了解详细信息。请您充分阅读并理解以上协议，点击同意按钮，即表示您已同意上述协议及以上约定。"

            //富文本
            val spannableStringBuilder = SpannableStringBuilder(content)
            val userAgreementStart =   content.indexOf(userAgreement) //《用户协议》起始位置
            val userAgreementEnd = userAgreementStart + userAgreement.length //《用户协议》结束位置
            val privacyPolicyStart = content.indexOf(privacyPolicy) //《隐私政策》起始位置
            val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length//《隐私政策》结束位置

            //用户协议
            spannableStringBuilder.setSpan(object :ClickableSpan(){
                override fun onClick(widget: View) {
                    Toast.makeText(this@SplashActivity,"点击了用户协议",Toast.LENGTH_SHORT).show()
                }
                //文字样式
                override fun updateDrawState(ds: TextPaint) {
                    ds.isUnderlineText = false
                    ds.color = colorMain

                }

            },userAgreementStart,userAgreementEnd,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)


            //隐私政策
            spannableStringBuilder.setSpan(object :ClickableSpan(){
                override fun onClick(widget: View) {
                    Toast.makeText(this@SplashActivity,"点击了隐私政策",Toast.LENGTH_SHORT).show()
                }
                //文字样式
                override fun updateDrawState(ds: TextPaint) {
                    ds.isUnderlineText = false
//                    ds.color = Color.RED 不建议 使用统一的属性风格
                    ds.color = colorMain
                }
            },privacyPolicyStart,privacyPolicyEnd,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)


            //温馨提示对话框
            MessageNoticeDialog(
                title = "温馨提示",
                message = spannableStringBuilder,
                confirmText = "同意",
                cancelText = "不同意",
                onConfirmClick = {
                    //同意
                    AppMMKV.splashAgreement = true
                    //记录当前版本号
                    AppMMKV.lastVersionCode = getVersionCode(this)
                    //2秒延迟
                    mHandler.sendEmptyMessageDelayed(2,SPLASH_MAX_DELAY)
                },
                onCancelClick = {
                    Toast.makeText(this,"点击了取消",Toast.LENGTH_SHORT).show()
                },
                alignment = Gravity.START
            ).show(supportFragmentManager)

        }else{
            //2秒延迟
            mHandler.sendEmptyMessageDelayed(2,SPLASH_MAX_DELAY)
        }

    }

    /**
     * 处理h5打开此app
     * @param type 类型跳转到指定页面
     * @param id  id
     */
    private fun handleLauchAppPramas(type: Int, id: String) {
        when(type){
            1 ->{
                Toast.makeText(this,"跳转车辆详情页 $id",Toast.LENGTH_SHORT).show()
            }
            2 ->{
                Toast.makeText(this,"跳转商品详情页 $id",Toast.LENGTH_SHORT).show()
            }
            3 ->{
                Toast.makeText(this,"跳转帖子详情页 $id",Toast.LENGTH_SHORT).show()
            }
            4 -> {
                Toast.makeText(this,"跳转动态详情页 $id",Toast.LENGTH_SHORT).show()
            }


        }
    }

    private fun toGuide(){
        ARouter.getInstance().build(Router.MAIN_GUIDE_ACTIVITY).navigation(this)
        actionAfterInitFinished?.invoke()
        finish()
    }

    private fun toMain(){
        ARouter.getInstance().build(Router.MAIN_MAIN_ACTIVITY).navigation(this)
        actionAfterInitFinished?.invoke()
        finish()
    }


    override fun initListener() {

    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)//移除未处理的消息，解决内存泄漏问题，重点话题
        actionAfterInitFinished = null
    }
}